package com.wangfugui.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangfugui.mybatisplus.dao.BeginningPriceDao;
import com.wangfugui.mybatisplus.domain.BeginningPrice;
import com.wangfugui.mybatisplus.service.BeginningPriceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;


@Service
@Slf4j
public class BeginningPriceServiceImpl extends ServiceImpl<BeginningPriceDao, BeginningPrice> implements BeginningPriceService {


    @Override
    public String getBeginningPrice(String stockCode, Date date) {
        if (stockCode == null || date == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 将 Date 转换为 LocalDate
        LocalDate targetDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        int year = targetDate.getYear(); // 获取年份

        // 构建查询条件：查询当年的数据，并按日期升序排序，取第一条（最早一条）
        LambdaQueryWrapper<BeginningPrice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BeginningPrice::getStockCode, stockCode)
                .ge(BeginningPrice::getDate, LocalDate.of(year, 1, 1)) // >= 当年第一天
                .lt(BeginningPrice::getDate, date)
                .lt(BeginningPrice::getDate, LocalDate.of(year + 1, 1, 1)) // < 下一年第一天
                .orderByAsc(BeginningPrice::getDate)
                .last("LIMIT 1"); // 按日期升序排列

        BeginningPrice firstRecord = this.getOne(wrapper);
        if (firstRecord != null) {
            return firstRecord.getPriceBeginningOfYear(); // 找到则返回
        }
        return null;
    }
}
